<script lang="ts" setup>
import { ref, watch } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { Button, message } from 'ant-design-vue';
import { useVbenForm } from '#/adapter/form';

const bandId = ref<number>(0);
const isDisabled = ref(true);

const [Modal, modalApi] = useVbenModal({
    appendToMain: true,
  // fullscreen: true,
  showConfirmButton: false,
  showCancelButton: false,
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const routerData = modalApi.getData<Record<string, any>>();
      bandId.value = 0;
      formApi.setValues({});
      if (routerData?.info?.id) {
        bandId.value = routerData.info.id;
      }

      if (bandId.value) {
        formApi.setValues(routerData.info);
        isDisabled.value = true;
      } else {
        isDisabled.value = false;
      }
    }
  },
});

watch(isDisabled, (val) => {
  formApi.setState({ commonConfig: { disabled: val } });
});

async function onSubmit() {
  const { valid } = await formApi.validate();
  if (valid) {
    const saveData = await formApi.getValues();
    modalApi.lock();
    try {
      if (bandId.value) {
        // await doBandEdit({ ...saveData, id: bandId.value });
        console.log('edit', saveData);
      } else {
        // await doBandAdd(saveData);
        console.log('add', saveData);
      }
      message.success('保存成功');
      modalApi.close();
    } finally {
      modalApi.lock(false);
    }
  }
}

const [Form, formApi] = useVbenForm({
  commonConfig: {
    disabled: isDisabled.value,
    componentProps: {
      class: 'w-full',
    },
  },
  showDefaultActions: false,
  layout: 'horizontal',
  schema: [
    {
      component: 'Input',
      fieldName: 'band_name',
      label: '波段名称',
      rules: 'required',
    },
  ],
});
</script>
<template>
  <Modal title="波段">
    <div class="p-4">
      <Form />
    </div>
    <template #prepend-footer>
      <Button @click="() => modalApi.close()">取消</Button>
      <Button v-if="!isDisabled || !bandId" type="primary" @click="onSubmit()">保存</Button>
    </template>
  </Modal>
</template>
